package com.fangngng.pushall.service.impl;

import com.fangngng.pushall.constant.ErrorCode;
import com.fangngng.pushall.entity.Role;
import com.fangngng.pushall.exception.BusinessException;
import com.fangngng.pushall.mapper.RoleMapper;
import com.fangngng.pushall.service.RoleService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;


/**
 * @author fei.fang
 * @date 2021/4/13
 **/
@Slf4j
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Role addRole(Role role) {

        List<Role> roleDb = roleMapper.select(role);
        if (!CollectionUtils.isEmpty(roleDb)) {
            throw new BusinessException(ErrorCode.ERROR_ROLE_EXIST);
        }

        roleMapper.insert(role);
        return role;
    }

    @Override
    public Role deleteRole(Role role) {
        if (role == null || role.getId() == null) {
            throw new BusinessException(ErrorCode.ERROR_PARAM_ERROR);
        }

        List<Role> roleDb = roleMapper.select(role);
        if (CollectionUtils.isEmpty(roleDb)) {
            throw new BusinessException(ErrorCode.ERROR_ROLE_NOT_EXIST);
        }

        roleMapper.deleteByPrimaryKey(role);
        return role;
    }

    @Override
    public Role editRole(Role role) {
        if (role == null || role.getId() == null) {
            throw new BusinessException(ErrorCode.ERROR_PARAM_ERROR);
        }

        List<Role> roleDb = roleMapper.select(role);
        if (CollectionUtils.isEmpty(roleDb)) {
            throw new BusinessException(ErrorCode.ERROR_ROLE_NOT_EXIST);
        }

        roleDb.get(0).setName(role.getName());
        roleMapper.updateByPrimaryKeySelective(roleDb.get(0));

        return roleDb.get(0);
    }

    @Override
    public List<Role> page(int pageNumber, int pageSize, Role role) {
        PageHelper.startPage(pageNumber, pageSize);
        List<Role> select = roleMapper.select(role);
        return select;
    }
}
